package com.atguigu.gmall.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.pay.config.AlipayTemplate;
import com.atguigu.gmall.pay.entity.PaymentInfoEntity;
import com.atguigu.gmall.pay.interceptor.OrderInterceptor;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayAsyncVo;
import com.atguigu.gmall.pay.vo.PayVo;
import com.atguigu.gmall.pms.entity.SkuEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PayController {

    @Autowired
    PayService payService;
    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String alipay(@RequestParam("orderToken") String orderToken, Model model){
        //查询订单信息
        OrderEntity orderEntity = payService.queryOrderByOrderToken(orderToken);
        if (orderEntity==null){
            throw new RuntimeException("订单为空");
        }
        //查询是否石次用户订单
        Long userId = OrderInterceptor.getUserInfo().getUserId();
        if (orderEntity.getUserId()!=userId){
            throw new RuntimeException("这个订单不属于您");
        }
        if (orderEntity.getStatus()!=0){
            throw new RuntimeException("这个订单不能支付");
        }

        model.addAttribute("orderEntity",orderEntity);
        return "pay";
    }

    @GetMapping("alipay.html")
    @ResponseBody // 以其他视图形式展示
    public String alipay(@RequestParam("orderToken")String orderToken){
        //查询订单信息
        OrderEntity orderEntity = payService.queryOrderByOrderToken(orderToken);
        if (orderEntity==null){
            throw new RuntimeException("订单为空");
        }
        //查询是否石次用户订单
        Long userId = OrderInterceptor.getUserInfo().getUserId();
        if (orderEntity.getUserId()!=userId){
            throw new RuntimeException("这个订单不属于您");
        }
        if (orderEntity.getStatus()!=0){
            throw new RuntimeException("这个订单不能支付");
        }
        PayVo payVo = new PayVo();
        payVo.setSubject("谷粒在线支付");
        payVo.setOut_trade_no(orderToken);
        payVo.setTotal_amount("0.01");

        //保存支付信息
        Long payId = payService.savePaymentInfo(payVo);
        payVo.setPassback_params(payId.toString());
        try {
            //返回支付页面
            String pay = alipayTemplate.pay(payVo);
            return pay;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("支付失败");
    }

    /**
     * 支付宝同步回调路径
     * @return
     */
    @GetMapping("pay/success")
    public String paySuccess(){

        return "paysuccess";
    }

    /**
     * 支付宝异步回调路径
     * @return
     */
    @PostMapping("pay/ok")
    @ResponseBody
    public Object payOk(PayAsyncVo payAsyncVo){

        // 1.验签
        Boolean flag = this.alipayTemplate.checkSignature(payAsyncVo);
        if (!flag) {
            return "failure";
        }

        // 2.校验订单的业务参数：app_id、out_trade_no、total_amount
        String appId = payAsyncVo.getApp_id();
        String outTradeNo = payAsyncVo.getOut_trade_no();
        String totalAmount = payAsyncVo.getTotal_amount();
        String payId = payAsyncVo.getPassback_params();
        PaymentInfoEntity paymentInfoEntity = this.payService.queryPaymentById(payId);
        if (!StringUtils.equals(appId, alipayTemplate.getApp_id())
                || !StringUtils.equals(outTradeNo, paymentInfoEntity.getOutTradeNo())
                || new BigDecimal(totalAmount).compareTo(paymentInfoEntity.getTotalAmount()) != 0
        ){
            return "failure";
        }

        // 3.校验支付状态码：trade_status  TRADE_SUCCESS
        if (!StringUtils.equals("TRADE_SUCCESS", payAsyncVo.getTrade_status())){
            return "failure";
        }

        // 4.更新对账表 已支付
        paymentInfoEntity.setPaymentStatus(1);
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(payAsyncVo));

        if (this.payService.updatePayment(paymentInfoEntity) == 0) {
            return "failure";
        }

        // 5.发送消息给oms修改订单状态，oms发送消息给wms减库存
        this.rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.pay",  outTradeNo);

        return "success";
    }
}
